package com.iwunu.iot.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by hepengpeng on 2018/6/19.
 */
public class MapToObjUtil {

    /**
     * 將map的参数值赋值给一个新对象
     * @param map
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T returnObj(Map map,Class clazz){
        try {
            return setValue(map,clazz.newInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }


    /**
     * 将map值复制给指定的对象
     * @param map
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> T returnObj(Map map,Object obj){
        return setValue(map,obj);
    }

    /**
     * 为对象赋值
     * @param map
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> T setValue(Map map,Object obj){
        try{
                    Method[] methods = obj.getClass().getMethods() ;
            String name = "" ;
            for(int i=0;i<methods.length;i++){
                name = methods[i].getName() ;
                if(name.contains("get")){
                    name = name.replace("get","") ;
                    for(Object key:map.keySet()){
                        if(key.toString().equalsIgnoreCase(name)){
                            if(map.get(key)!=null){
                                Field f = obj.getClass().getDeclaredField(key.toString());
                                if(f.getType().getSimpleName().contains("List")){
                                    continue;
                                }
                                f.setAccessible(true);
                                f.set(obj,formatType(f.getType().getSimpleName(),map.get(key)));
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace() ;
        }
        return (T) obj;
    }

    public static Object formatType(String typeName,Object obj){
        switch (typeName){
            case "Long" :
                return Long.valueOf(obj.toString()) ;
            case "Integer" :
                return Integer.valueOf(obj.toString()) ;
        }
        return obj.toString() ;
    }

}
